package org.mm.proxycache.http.codec;

import org.apache.mina.common.IoBuffer;
import org.apache.mina.common.IoSession;
import org.apache.mina.filter.codec.ProtocolEncoderOutput;
import org.mm.proxycache.http.HttpChunk;
import org.mm.proxycache.http.HttpResponse;

public class HttpResponseEncoder extends HttpEncoder
{

    public void encode( IoSession session, Object message, ProtocolEncoderOutput out )
            throws Exception
    {
        if ( message instanceof HttpChunk )
        {
            HttpChunk chunk = (HttpChunk) message;
            encodeChunk( chunk, out );
            return;
        }

        HttpResponse resp = (HttpResponse) message;

        IoBuffer buf = IoBuffer.allocate( 512, false );
        buf.setAutoExpand( true );

        buf.putString( resp.version().toString(), charsetEncoder );
        buf.put( (byte) ' ' );
        buf.putString( Integer.toString( resp.status().getCode() ), charsetEncoder );
        buf.put( (byte) ' ' );
        buf.putString( resp.statusReasonPhrase(), charsetEncoder );

        encode( resp, buf );

        if ( resp instanceof CompleteHttpResponse )
        {
            CompleteHttpResponse response = (CompleteHttpResponse) resp;
            buf.put( response.data() );
        }

        buf.flip();
        out.write( buf );

        // if ( (resp instanceof CompleteHttpResponse)
     //         || (resp.getContentLength() == 0 && !"chunked".equals( resp
     //                 .getHeader( "Trasnfer-Encoding" ) )) )
     //     out.flush();
    }

}
